package com.zxxy.gulimall.testssoclient.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class Hello2Controller {

    // 无需登录就可访问
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){

        return "hello";
    }


    // 感知这次实在sso登录成功跳回来的
    // 只要去sso登录成功调回来的就会带上
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token){

        if (!StringUtils.isEmpty(token)){
            //去sso登录成功跳回来就会带上
            // TODO 1、去sso获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            // 没登录，跳转到登录服务器进行登录


            // 跳转过去以后  使用url上的查询参数标识我们自己是哪个页面
            // redirect_url=http://client1.com:8080/employees
            return "redirect:http://sso.com:8080/login.html?redirect_url=http://client2.com:8082/boss";
        }else {
            List<String> emps = new ArrayList<>();
            emps.add("zhangsan");
            emps.add("lisi");
            model.addAttribute("emps",emps);
            return "list";
        }
    }

}
